package com.hurt.competition.player.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hurt.competition.player.mapper.CompetitionJudgePlayerMapper;
import com.hurt.competition.player.model.CompetitionJudgePlayer;
import com.hurt.competition.player.model.CompetitionPlayer;
import com.hurt.competition.player.service.CompetitionJudgePlayerService;
import com.hurt.competition.player.service.CompetitionPlayerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
public class CompetitionJudgePlayerServiceImpl extends ServiceImpl<CompetitionJudgePlayerMapper, CompetitionJudgePlayer> implements CompetitionJudgePlayerService {

    @Autowired
    private CompetitionPlayerService competitionPlayerService;

    @Override
    public void scoring(CompetitionJudgePlayer competitionJudgePlayer) {
        competitionJudgePlayer.setJudgeTime(new Date());
        this.save(competitionJudgePlayer);

        // 计算平均分
        //updatePlayerScore(competitionJudgePlayer.getGId(),competitionJudgePlayer.getPId());
    }

    public void updatePlayerScore(Integer competitionId) {
        List<CompetitionJudgePlayer> judgePlayers = this.list(new LambdaQueryWrapper<CompetitionJudgePlayer>() {{
            eq(CompetitionJudgePlayer::getCompetitionId, competitionId);
        }});

        CompetitionPlayer competitionPlayer = new CompetitionPlayer();
        competitionPlayer.setCompetitionId(competitionId);

        if(CollectionUtils.isEmpty(judgePlayers)){
            competitionPlayer.setScore(new BigDecimal("0"));
        } else {
            double averageScore = judgePlayers.stream()
                    .mapToDouble(player -> player.getScore().doubleValue())
                    .average()
                    .orElse(0.0);
            competitionPlayer.setScore(new BigDecimal(averageScore));
        }
        competitionPlayerService.scoring(competitionPlayer);
    }

}
